import React from 'react';
import _, { parseInt } from 'lodash';
import menuConfigMap from '@/VisualEditingPackage/config/menuConfigMap';
import classnames from 'classnames';
import { toolButtons } from '../../config/config';

const Canvas = ({ data, setData, clearFocus }) => {
  const blockOnMouseDown = (e, key) => {
    e.stopPropagation();
    const newData = clearFocus(data);
    newData[key].focus = true;
    setData(newData);
    const defaultPosition = {
      x: e.clientX - parseInt(e.target.style.left, 10),
      y: e.clientY - parseInt(e.target.style.top, 10),
    };
    document.onmousemove = (event) => {
      const position = {
        left: event.clientX - defaultPosition.x,
        top: event.clientY - defaultPosition.y,
      };
      const newData = clearFocus(data);
      newData[key].style = position;
      newData[key].focus = true;
      setData(newData);
      return false;
    };
    document.onmouseup = () => {
      document.onmousemove = null;
    };
  };
  return (
    <div id="blocks">
      <div className="tools_header">{_.map(toolButtons, (item, key) => {})}</div>
      {_.map(data, (item, key) => {
        const Component = item.component ? menuConfigMap[item.component] : null;
        return (
          <div
            key={item.id + '_' + key}
            className={classnames('block-item', {
              'block-item-active': item.focus,
            })}
            style={{ ...item.style }}
            onMouseDown={(e) => blockOnMouseDown(e, key)}
          >
            {Component && <Component />}
          </div>
        );
      })}
    </div>
  );
};

export default Canvas;
